/**
 菜单显示异常修改tinymce/skins/ui/oxide/skin.min.css:96 .tox-silver-sink的z-index值
 http://tinymce.ax-z.cn/   中文文档
 */

layui.define(['jquery', 'layer','filechoose'], function (exports) {
    var $ = layui.$,
        modFile = layui.cache.modules['tinymce'],
        modPath = modFile.substr(0, modFile.lastIndexOf('.')),
        setter = layui.setter,
        response = setter.response,
        filechoose = layui.filechoose,
        tiny = { path: 'tiny' },
        settings = {
            base_url: modPath,//设置主程序结构所在url
            language: 'zh_CN',//界面语言
            resize: false,//调整编辑器大小工具
            elementpath: false,//隐藏底栏的元素路径
            branding: false,//隐藏右下角技术支持
            contextmenu_never_use_native: true,//在编辑器中屏蔽浏览器本身的右键菜单
            quickbars_selection_toolbar: "cut copy | bold italic underline strikethrough",//[选择]快捷工具栏
            insertdatetime_formats: ["%Y年%m月%d日", "%H点%M分", "%A", "%p"],//日期时间格式
            selector: ".editor",//DOM
            plugins: "quickbars print preview searchreplace autolink fullscreen image link media codesample table charmap hr advlist lists wordcount imagetools indent2em fullscreen insertdatetime code",//指定需加载的插件
            toolbar: "fullscreen | undo redo | forecolor backcolor bold italic underline strikethrough | indent2em alignleft aligncenter alignright alignjustify outdent indent | bullist numlist",//自定义工具栏
            menubar: "file edit insert format tablef",//1级菜单
            //自定义菜单
            menu: {
                file: {
                    title: '文件',
                    items: 'newdocument | print preview fullscreen | wordcount'
                },
                edit: {
                    title: '编辑',
                    items: 'undo redo | cut copy paste pastetext selectall | code searchreplace'
                },
                format: {
                    title: '格式',
                    items: 'bold italic underline strikethrough superscript subscript | formats | forecolor backcolor | removeformat'
                },
                table: {
                    title: '表格',
                    items: 'inserttable tableprops deletetable | cell row column'
                },
            },
            //图片上传自定义实现
            images_upload_handler: function (blobInfo, succFun, failFun) {
                var xhr,
                    formData,
                    json,
                    file = blobInfo.blob(),
                    size = 10240 * 1024;
                if (file.size > size) {
                    failFun('图片上传大小限制:10M ');
                }
                formData = new FormData();
                formData.append("path", tiny.path);
                formData.append("size", size);
                formData.append("file", file, file.name);
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('post', '/api/file/blobinfo');
                xhr.send(formData);
                xhr.onload = function () {
                    if (xhr.status != response.statusCode.ok) {
                        failFun('HTTP Error: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json[response.dataName] != 'string') {
                        failFun('Invalid JSON: ' + xhr.responseText);
                        return;
                    }
                    succFun(setter.sysDomain + json[response.dataName]);
                };
            },
            //文件上传自定义实现
            file_picker_callback: function (callback, value, meta) {
                filechoose.open({
                    fileUrl: setter.sysDomain,
                    listUrl: '/api/file/list?v=' + layui.cache.version,
                    editorUrl: '/api/file/editor?v=' + layui.cache.version,
                    delUrl: '/api/file/delete?v=' + layui.cache.version,
                    where: {
                        path: tiny.path
                    },
                    upload: {
                        url: '/api/file/upload?v=' + layui.cache.version,
                        mergeUrl: '/api/file/merge?v=' + layui.cache.version,
                        multiple: true,
                        accept: 'file',
                        number: 20,
                        exts: 'jpg|png|gif|bmp|rar|zip|pdf|xls|txt|doc|xlsx|docx|ogg|mp4|flv',
                        size: 307200,
                        msgAtt: { zIndex: 99999999 }
                    },
                    dialog: {
                        area: ['605px', '80%'],
                        title: '选择文件',
                        zIndex: 99999999
                    },
                    onChoose: function (urls) {
                        switch (meta.filetype) {
                            case 'file':
                                callback(setter.sysDomain + urls[0].url, { text: urls[0].name });
                                break;
                            case 'image':
                                callback(setter.sysDomain + urls[0].url, { alt: urls[0].name });
                                break;
                            case 'media':
                                callback(setter.sysDomain + urls[0].url, { source2: '', poster: '' });
                                break;
                        };
                    }
                });
            }
        },
        script = function () {
            var start,
                end,
                defer = $.Deferred();
            $.ajax({
                url: modPath + '/tinymce.js',
                dataType: 'script',
                cache: true,
                beforeSend: function () {
                    start = new Date().getTime();
                },
                complete: function () {
                    end = new Date().getTime();
                },
                success: function () {
                    defer.resolve(end - start);
                }
            });
            return defer.promise();
        };

    tiny.render = function (option) {
        option.base_url = option.base_url ? option.base_url : settings.base_url; //设置主程序结构所在url
        option.language = option.language ? option.language : settings.language; //界面语言
        option.selector = option.selector ? option.selector : settings.selector; //实例DOM
        option.quickbars_selection_toolbar = option.quickbars_selection_toolbar ? option.quickbars_selection_toolbar : settings.quickbars_selection_toolbar;  //[选择]快捷工具栏
        option.plugins = option.plugins ? option.plugins : settings.plugins; //指定需加载的插件
        option.toolbar = option.toolbar ? option.toolbar : settings.toolbar; //自定义工具栏
        option.resize = option.resize ? option.resize : settings.resize; //调整编辑器大小工具
        option.elementpath = option.elementpath ? option.elementpath : settings.elementpath; //隐藏底栏的元素路径
        option.branding = option.branding ? option.branding : settings.branding; //隐藏右下角技术支持
        option.contextmenu_never_use_native = option.contextmenu_never_use_native ? option.contextmenu_never_use_native : settings.contextmenu_never_use_native; //在编辑器中屏蔽浏览器本身的右键菜单
        option.menubar = option.menubar ? option.menubar : settings.menubar; //1级菜单
        option.insertdatetime_formats = option.insertdatetime_formats ? option.insertdatetime_formats : settings.insertdatetime_formats; //日期时间格式
        option.images_upload_handler = option.images_upload_handler ? option.images_upload_handler : settings.images_upload_handler; //图片上传自定义实现
        option.file_picker_callback = option.file_picker_callback ? option.file_picker_callback : settings.file_picker_callback; //文件上传自定义实现
        option.menu = option.menu ? option.menu : settings.menu; //自定义菜单
        $.when(script()).then(function (res) {
            setTimeout(function () {
                tinymce.init(option);
                tiny.tinymce = tinymce;
                return tinymce.activeEditor;
            }, res);
        });
    };
    exports('tinymce', tiny);
});